<template>
  <div class="order-progress-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>服务进度</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 订单基本信息 -->
      <el-card class="order-info-card" v-loading="loading">
        <div v-if="orderInfo" class="order-summary">
          <div class="order-header">
            <div class="order-number">
              订单号：{{ orderInfo.orderNumber }}
              <el-tag :type="getStatusType(orderInfo.status)" size="small">
                {{ getStatusText(orderInfo.status) }}
              </el-tag>
            </div>
            <div class="order-time">{{ formatDate(orderInfo.createdAt) }}</div>
          </div>

          <div class="service-info">
            <div class="service-image">
              <el-image
                :src="orderInfo.service?.image || '/default-service.jpg'"
                fit="cover"
                class="image"
              />
            </div>
            <div class="service-details">
              <h3>{{ orderInfo.service?.name }}</h3>
              <p class="merchant-name">{{ orderInfo.merchant?.name }}</p>
              <div class="order-meta">
                <span>数量：{{ orderInfo.quantity }}{{ orderInfo.service?.unit }}</span>
                <span>金额：¥{{ orderInfo.totalAmount }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 进度步骤 -->
      <el-card class="progress-card">
        <template #header>
          <h3>服务进度</h3>
        </template>

        <el-steps 
          :active="currentStep" 
          direction="vertical" 
          class="progress-steps"
          finish-status="success"
        >
          <el-step 
            v-for="(step, index) in progressSteps"
            :key="index"
            :title="step.title"
            :description="step.description"
            :status="getStepStatus(index)"
          >
            <template #icon>
              <el-icon :size="24" :color="getStepIconColor(index)">
                <component :is="step.icon" />
              </el-icon>
            </template>
          </el-step>
        </el-steps>
      </el-card>

      <!-- 详细进度记录 -->
      <el-card class="progress-timeline-card">
        <template #header>
          <h3>进度详情</h3>
        </template>

        <el-timeline class="progress-timeline">
          <el-timeline-item
            v-for="(record, index) in progressRecords"
            :key="index"
            :timestamp="formatDateTime(record.timestamp)"
            :type="getTimelineType(record.status)"
            :color="getTimelineColor(record.status)"
            placement="top"
          >
            <el-card class="timeline-card" :body-style="{ padding: '16px' }">
              <div class="timeline-content">
                <div class="timeline-header">
                  <h4>{{ record.title }}</h4>
                  <el-tag :type="getRecordTagType(record.status)" size="small">
                    {{ record.statusText }}
                  </el-tag>
                </div>
                <p class="timeline-description">{{ record.description }}</p>
                <div class="timeline-meta" v-if="record.operator">
                  <span>操作人：{{ record.operator }}</span>
                  <span v-if="record.location">地点：{{ record.location }}</span>
                </div>
                <div class="timeline-images" v-if="record.images?.length">
                  <el-image
                    v-for="(image, imageIndex) in record.images"
                    :key="imageIndex"
                    :src="image"
                    fit="cover"
                    class="timeline-image"
                    @click="previewImage(image)"
                  />
                </div>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>

      <!-- 服务信息 -->
      <el-card class="service-details-card" v-if="orderInfo">
        <template #header>
          <h3>服务信息</h3>
        </template>

        <div class="service-details-content">
          <div class="detail-item">
            <span class="label">预约时间：</span>
            <span class="value">
              {{ formatDate(orderInfo.appointmentDate) }} {{ orderInfo.appointmentTime }}
            </span>
          </div>
          
          <div class="detail-item" v-if="orderInfo.address">
            <span class="label">服务地址：</span>
            <div class="address-value">
              <div>{{ orderInfo.address.fullAddress }}</div>
              <div class="contact-info">
                {{ orderInfo.address.contactName }} {{ orderInfo.address.contactPhone }}
              </div>
            </div>
          </div>

          <div class="detail-item" v-if="orderInfo.note">
            <span class="label">备注信息：</span>
            <span class="value">{{ orderInfo.note }}</span>
          </div>

          <div class="detail-item" v-if="estimatedTime">
            <span class="label">预计完成：</span>
            <span class="value estimated-time">{{ estimatedTime }}</span>
          </div>
        </div>
      </el-card>

      <!-- 联系方式 -->
      <el-card class="contact-card">
        <template #header>
          <h3>联系方式</h3>
        </template>

        <div class="contact-buttons">
          <el-button 
            type="primary" 
            @click="contactMerchant"
            :icon="ChatDotRound"
            size="large"
          >
            联系商家
          </el-button>
          
          <el-button 
            @click="contactService"
            :icon="Phone"
            size="large"
          >
            客服热线
          </el-button>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons" v-if="orderInfo">
        <el-button 
          v-if="canCancel"
          @click="cancelOrder"
          size="large"
        >
          取消订单
        </el-button>
        
        <el-button 
          v-if="canConfirm"
          type="primary"
          @click="confirmService"
          size="large"
        >
          确认完成
        </el-button>
        
        <el-button 
          v-if="canRate"
          type="primary"
          @click="goToRating"
          size="large"
        >
          评价服务
        </el-button>
      </div>
    </div>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="previewImages"
      :initial-index="currentImageIndex"
      @close="showImageViewer = false"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  ChatDotRound,
  Phone,
  Clock,
  Checked,
  Loading,
  Tools,
  Star
} from '@element-plus/icons-vue'
import { orderApi } from '@/services/api'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 数据定义
const loading = ref(true)
const orderInfo = ref(null)
const progressRecords = ref([])
const currentStep = ref(0)
const refreshTimer = ref(null)
const showImageViewer = ref(false)
const previewImages = ref([])
const currentImageIndex = ref(0)

// 进度步骤定义
const progressSteps = ref([
  {
    title: '订单确认',
    description: '商家已接收订单，正在准备服务',
    icon: Checked
  },
  {
    title: '服务准备',
    description: '工作人员正在准备相关工具和材料',
    icon: Tools
  },
  {
    title: '开始服务',
    description: '工作人员已到达现场，开始提供服务',
    icon: Loading
  },
  {
    title: '服务完成',
    description: '服务已完成，请确认服务质量',
    icon: Star
  }
])

// 计算属性
const estimatedTime = computed(() => {
  if (!orderInfo.value || !orderInfo.value.estimatedCompletionTime) return null
  return formatDateTime(orderInfo.value.estimatedCompletionTime)
})

const canCancel = computed(() => {
  return orderInfo.value && ['paid', 'confirmed'].includes(orderInfo.value.status)
})

const canConfirm = computed(() => {
  return orderInfo.value && orderInfo.value.status === 'in_service'
})

const canRate = computed(() => {
  return orderInfo.value && orderInfo.value.status === 'completed' && !orderInfo.value.isRated
})

// 生命周期
onMounted(() => {
  const orderId = route.params.id
  if (orderId) {
    fetchOrderProgress(orderId)
    // 设置定时刷新
    refreshTimer.value = setInterval(() => {
      fetchOrderProgress(orderId)
    }, 30000) // 30秒刷新一次
  }
})

onUnmounted(() => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }
})

// 方法定义
const fetchOrderProgress = async (orderId) => {
  try {
    loading.value = true
    const response = await orderApi.getOrderProgress(orderId)
    const data = response.data
    
    orderInfo.value = data.order
    progressRecords.value = data.progressRecords || []
    currentStep.value = data.currentStep || 0
  } catch (error) {
    console.error('获取订单进度失败:', error)
    
    // 使用模拟数据
    const mockOrderId = parseInt(orderId)
    orderInfo.value = {
      id: mockOrderId,
      orderNumber: `202412280${mockOrderId.toString().padStart(3, '0')}`,
      status: 'in_service',
      createdAt: new Date(Date.now() - 3600000),
      appointmentDate: '2024-12-29',
      appointmentTime: '14:00-15:00',
      merchant: {
        id: 1,
        name: '专业洗护店',
        phone: '400-123-4567'
      },
      service: {
        id: 1,
        name: '高档衣物干洗',
        price: 35,
        unit: '件',
        image: '/default-service.jpg'
      },
      address: {
        fullAddress: '北京市朝阳区三里屯SOHO 1号楼1001室',
        contactName: '张三',
        contactPhone: '138****1234'
      },
      quantity: 2,
      totalAmount: 65,
      note: '请小心处理',
      estimatedCompletionTime: new Date(Date.now() + 1800000),
      isRated: false
    }
    
    progressRecords.value = [
      {
        title: '订单已确认',
        description: '商家已接收您的订单，正在安排服务人员',
        status: 'completed',
        statusText: '已完成',
        timestamp: new Date(Date.now() - 3600000),
        operator: '系统',
        location: '线上'
      },
      {
        title: '服务准备中',
        description: '工作人员正在准备服务工具和材料，预计10分钟后到达',
        status: 'completed',
        statusText: '已完成',
        timestamp: new Date(Date.now() - 1800000),
        operator: '李师傅',
        location: '专业洗护店'
      },
      {
        title: '服务开始',
        description: '工作人员已到达服务地点，开始提供洗护服务',
        status: 'in_progress',
        statusText: '进行中',
        timestamp: new Date(Date.now() - 900000),
        operator: '李师傅',
        location: '服务地址',
        images: ['/service-progress-1.jpg', '/service-progress-2.jpg']
      }
    ]
    
    currentStep.value = 2
    
    ElMessage.error('获取订单进度失败，显示模拟数据')
  } finally {
    loading.value = false
  }
}

const handleBack = () => {
  router.back()
}

const contactMerchant = () => {
  if (orderInfo.value?.merchantId) {
    router.push(`/chat/${orderInfo.value.merchantId}?orderId=${orderInfo.value.id}`)
  }
}

const contactService = () => {
  window.open('tel:400-123-4567')
}

const cancelOrder = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？取消后无法恢复。',
      '取消订单',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '我再想想',
        type: 'warning'
      }
    )

    await orderApi.cancelOrder(orderInfo.value.id)
    
    ElMessage.success('订单已取消')
    router.push('/orders')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

const confirmService = async () => {
  try {
    await ElMessageBox.confirm(
      '确认服务已完成？确认后订单将进入评价阶段。',
      '确认完成',
      {
        confirmButtonText: '确认完成',
        cancelButtonText: '还未完成',
        type: 'info'
      }
    )

    await orderApi.confirmService(orderInfo.value.id)
    
    ElMessage.success('服务已确认完成')
    // 刷新页面数据
    fetchOrderProgress(orderInfo.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认服务失败:', error)
      ElMessage.error('确认服务失败')
    }
  }
}

const goToRating = () => {
  router.push(`/orders/${orderInfo.value.id}/rating`)
}

const previewImage = (image) => {
  previewImages.value = [image]
  currentImageIndex.value = 0
  showImageViewer.value = true
}

const getStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    paid: 'primary',
    confirmed: 'primary',
    in_service: 'primary',
    completed: 'success',
    cancelled: 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待支付',
    paid: '已支付',
    confirmed: '已确认',
    in_service: '服务中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || '未知状态'
}

const getStepStatus = (index) => {
  if (index < currentStep.value) return 'finish'
  if (index === currentStep.value) return 'process'
  return 'wait'
}

const getStepIconColor = (index) => {
  if (index < currentStep.value) return '#67c23a'
  if (index === currentStep.value) return '#409eff'
  return '#c0c4cc'
}

const getTimelineType = (status) => {
  const typeMap = {
    completed: 'success',
    in_progress: 'primary',
    pending: 'warning',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

const getTimelineColor = (status) => {
  const colorMap = {
    completed: '#67c23a',
    in_progress: '#409eff',
    pending: '#e6a23c',
    failed: '#f56c6c'
  }
  return colorMap[status] || '#909399'
}

const getRecordTagType = (status) => {
  const typeMap = {
    completed: 'success',
    in_progress: 'primary',
    pending: 'warning',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}
</script>

<style lang="scss" scoped>
.order-progress-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.order-info-card {
  .order-summary {
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 16px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;

      .order-number {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .order-time {
        color: #999;
        font-size: 14px;
      }
    }

    .service-info {
      display: flex;
      gap: 12px;

      .service-image {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        overflow: hidden;
        flex-shrink: 0;

        .image {
          width: 100%;
          height: 100%;
        }
      }

      .service-details {
        flex: 1;

        h3 {
          margin: 0 0 4px 0;
          font-size: 16px;
          color: #333;
        }

        .merchant-name {
          margin: 0 0 8px 0;
          color: #666;
          font-size: 14px;
        }

        .order-meta {
          display: flex;
          gap: 16px;
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

.progress-card {
  .progress-steps {
    margin: 20px 0;

    :deep(.el-step__description) {
      color: #666;
      font-size: 14px;
      line-height: 1.4;
    }
  }
}

.progress-timeline-card {
  .progress-timeline {
    margin-top: 20px;

    .timeline-card {
      border: none;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .timeline-content {
      .timeline-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 8px;

        h4 {
          margin: 0;
          font-size: 16px;
          color: #333;
        }
      }

      .timeline-description {
        margin: 0 0 12px 0;
        color: #666;
        line-height: 1.5;
      }

      .timeline-meta {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: #999;
        margin-bottom: 12px;
      }

      .timeline-images {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;

        .timeline-image {
          width: 60px;
          height: 60px;
          border-radius: 4px;
          cursor: pointer;
          transition: transform 0.3s ease;

          &:hover {
            transform: scale(1.1);
          }
        }
      }
    }
  }
}

.service-details-card {
  .service-details-content {
    display: flex;
    flex-direction: column;
    gap: 16px;

    .detail-item {
      display: flex;
      align-items: flex-start;
      gap: 8px;

      .label {
        color: #666;
        font-size: 14px;
        white-space: nowrap;
        min-width: 80px;
      }

      .value {
        color: #333;
        font-size: 14px;
        flex: 1;

        &.estimated-time {
          color: #409eff;
          font-weight: 500;
        }
      }

      .address-value {
        flex: 1;

        .contact-info {
          color: #999;
          font-size: 12px;
          margin-top: 4px;
        }
      }
    }
  }
}

.contact-card {
  .contact-buttons {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 24px;
  margin-bottom: 40px;

  .el-button {
    flex: 1;
    height: 48px;
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .order-info-card .service-info {
    flex-direction: column;
    text-align: center;

    .service-image {
      align-self: center;
    }
  }

  .progress-steps {
    :deep(.el-step) {
      .el-step__head {
        width: 100%;
      }
    }
  }

  .contact-buttons {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .action-buttons {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style> 